
package com.example.myproject.controller;

import com.example.myproject.model.Role;
import com.example.myproject.service.RoleService;
import com.example.myproject.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @PostMapping("/add")
    public Result<Role> createRole(@RequestBody Role role) {
        Role createdRole = roleService.createRole(role);
        if(role!=null){
            return Result.success(createdRole,"新建角色成功！");

        }else{
            return Result.error("123","新建角色失败！");
        }
    }


    @GetMapping("/get")
    public Result<List<Role>> getAllRoles() {
        List<Role> roles = roleService.getAllRoles();
        return Result.success(roles, "查找所有角色成功！");
    }

    @GetMapping("/{name}")
    public Result<List<Role>> searchRolesByName(@RequestParam(required = false) String name) {
        if (name == null || name.isEmpty()) {
            // 如果接收内容为空，则调用已经存在的查找所有角色的方法
            return getAllRoles();
        } else {
            List<Role> roles = roleService.searchRolesByName(name);
            if (!roles.isEmpty()) {
                return Result.success(roles, "根据角色名搜索角色成功！");
            } else {
                return Result.error("404", "没有找到符合条件的角色！");
            }
        }
    }


    @PutMapping("/edit/{name}")
    public Result<Role> updateRole(@PathVariable String name, @RequestBody Role roleDetails) {
        Role updatedRole = roleService.updateRole(name, roleDetails);
        if(updatedRole!=null){

            return Result.success(updatedRole,"修改角色成功！");

        }else{
            return Result.error("123","修改角色失败！");
        }
    }

    @DeleteMapping("/delete/{name}")
    public Result<Role>  deleteRole(@PathVariable String name) {
        roleService.deleteRole(name);
        return Result.success(null, "删除角色成功！");
    }
}
